package com.aztech.app;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.NetworkSpecifier;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiNetworkSpecifier;
import android.os.Bundle;
import android.os.Handler;
import android.os.PatternMatcher;
import android.provider.Settings;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.huawei.hms.framework.common.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class WifiActivity extends AppCompatActivity {

    private Button connectButton;
    private Button testWOIButton;
    private Button testEQSButton;

    private EditText wifiSsidEditText;
    private EditText wifiPwdEditText;
    private TextView logTextView;
    private ProgressBar logProgressBar;

    //多线程时是不允许操作ui，需要使用handler是处理
    private static Handler handler = new Handler();
    //WIFI管理服务
    private WifiManager wifiManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi);

        wifiSsidEditText = (EditText) findViewById(R.id.wifiSsidEditText);
        wifiPwdEditText = (EditText) findViewById(R.id.wifiPwdEditText);
        logTextView = (TextView) findViewById(R.id.logTextView);
        logProgressBar = (ProgressBar) findViewById(R.id.logProgressBar);

        //设置WIFI服务
        wifiManager = (WifiManager) WifiActivity.this.getApplicationContext().getSystemService(WifiActivity.this.WIFI_SERVICE);
        //设置已保存的WIFI参数
        SharedPreferences sp = WifiActivity.this.getSharedPreferences("AZTECH", MODE_PRIVATE);
        wifiSsidEditText.setText(sp.getString("ssid", "AZGRP"));
        wifiPwdEditText.setText(sp.getString("pwd", "l1nk4empl0yee"));

        connectButton = (Button) findViewById(R.id.connectButton);
        connectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String wifiSsid = wifiSsidEditText.getText().toString();
                String wifiPwd = wifiPwdEditText.getText().toString();

                if (wifiSsid.equals("") || wifiPwd.equals("")) {
                    Toast.makeText(WifiActivity.this, "Please input wifi SSID and password!",Toast.LENGTH_SHORT).show();
                } else {
                    //存入WIFI数据
                    SharedPreferences sp = WifiActivity.this.getSharedPreferences("AZTECH", MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("ssid", wifiSsid);
                    editor.putString("pwd", wifiPwd);
                    editor.commit();
                    connectWifi(wifiSsid, wifiPwd);
                }
            }
        });

        testWOIButton = (Button) findViewById(R.id.testWOIButton);
        testWOIButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pingWebServer("10.10.8.35");
            }
        });

        testEQSButton = (Button) findViewById(R.id.testEQSButton);
        testEQSButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pingWebServer("10.10.8.95");
            }
        });
    }

    //测试服务器网络延时
    private void pingWebServer(final String serverIP) {
        logProgressBar.setVisibility(View.VISIBLE);
        logTextView.setText("");
        //异步调试网络延时
        new Thread(new Runnable() {
            @Override
            public void run() {
                Process p =null;
                try{
                    p = Runtime.getRuntime().exec("/system/bin/ping -c 10 " + serverIP);
                    BufferedReader buf =new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String str =new String();
                    while((str = buf.readLine()) != null){
                        final String message = str;
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                logProgressBar.setVisibility(View.INVISIBLE);
                                logTextView.append("\n");
                                logTextView.append(message);
                            }
                        });
                    }
                }catch(IOException e) {
                    final String message = e.getMessage();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            logTextView.append("\n");
                            logTextView.append(message);
                        }
                    });
                }
            }
        }).start();
    }

    private void connectWifi(String ssid, String pwd) {
        logTextView.setText("");
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                //Android 10+ 连接WIFI
                if (!wifiManager.isWifiEnabled()) {
                    //10+无法通过代码打开wifi，只能手动设定
                    logTextView.append("WIFI not available, Please open WIFI first.\n");
                    return;
                }

                NetworkSpecifier specifier = new WifiNetworkSpecifier.Builder()
                                .setSsidPattern(new PatternMatcher(ssid, PatternMatcher.PATTERN_PREFIX))
                                .setWpa2Passphrase(pwd)
                                .build();

                NetworkRequest request = new NetworkRequest.Builder()
                                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                                .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                                .setNetworkSpecifier(specifier)
                                .build();

                ConnectivityManager connectivityManager = (ConnectivityManager) WifiActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
                ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onAvailable(Network network) {
                        WifiInfo info = wifiManager.getConnectionInfo();
                        int ipAddress = info.getIpAddress();
                        if (ipAddress != 0) {
                            final String ipString = ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    logTextView.append("\n");
                                    logTextView.append("Success obtain IP Address: " + ipString);
                                }
                            });
                        }
                    }

                    @Override
                    public void onUnavailable() {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                logTextView.append("\n");
                                logTextView.append("Faile obtain IP Address! Please try it later. ");
                            }
                        });
                    }
                };
                connectivityManager.requestNetwork(request, networkCallback);

            } else {
                //Android 9- 连接WIFI
                if (!wifiManager.isWifiEnabled()) {
                    logTextView.append("WIFI not available, opeing WIFI now ......\n");
                    wifiManager.setWifiEnabled(true);
                    logTextView.append("Open WIFI successfully.\n");
                }

                if (!isGpsOpen()) {
                    logTextView.append("GPS not available, opeing GPS now ......\n");
                    AlertDialog.Builder builder = new AlertDialog.Builder(WifiActivity.this);
                    builder.setMessage("Please open GPS first.")
                            .setCancelable(false)
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                    startActivity(intent);
                                    dialog.dismiss();
                                }
                            });
                    AlertDialog alert = builder.create();
                    alert.show();
                    return;
                }

                logTextView.append("Scan available network .......\n\n");
                List<ScanResult> scanResults = wifiManager.getScanResults();
                for (ScanResult scanResult : scanResults) {
                    String bssid = scanResult.SSID;
                    logTextView.append(bssid);
                    logTextView.append("\n");
                }

                logTextView.append("\n");
                int networkID = 0;
                WifiConfiguration config = getExistsWifiConfiguration(ssid);
                if (config != null) {
                    logTextView.append("Netowrk [" + ssid + "] already saved, now connecting ......\n");
                    networkID = config.networkId;
                } else {
                    logTextView.append("First time connect network [" + ssid + "]，now connecting ......\n");
                    //初始化WifiConfiguration
                    config = new WifiConfiguration();
                    config.allowedAuthAlgorithms.clear();
                    config.allowedGroupCiphers.clear();
                    config.allowedKeyManagement.clear();
                    config.allowedPairwiseCiphers.clear();
                    config.allowedProtocols.clear();
                    //指定对应的SSID
                    config.SSID = "\"" + ssid + "\"";
                    //以WPA加密的场景
                    config.preSharedKey = "\""+ pwd +"\"";
                    config.hiddenSSID = true;
                    config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                    config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                    config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                    config.status = WifiConfiguration.Status.ENABLED;
                    //接入网络
                    networkID = wifiManager.addNetwork(config);
                }

                boolean isEnabled = wifiManager.enableNetwork(networkID, true);
                if (isEnabled) {
                    logTextView.append("Success connected network [" + ssid + "]\n");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                int startTime = 0;
                                int maxWaitTime = 60000;
                                while(startTime < maxWaitTime){
                                    WifiInfo info = wifiManager.getConnectionInfo();
                                    int ipAddress = info.getIpAddress();
                                    if (ipAddress != 0) {
                                        final String ipString = ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
                                        handler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                logTextView.append("\n");
                                                logTextView.append("Success obtain IP Address: " + ipString);
                                            }
                                        });
                                        return;
                                    } else {
                                        startTime = startTime + 2000;
                                        Thread.sleep(2000);
                                        handler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                logTextView.append("Obtaining IP Address ...... \n");
                                            }
                                        });
                                    }
                                }

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        logTextView.append("\n");
                                        logTextView.append("Fail to obtain IP Address, please try again later. ");
                                    }
                                });
                            } catch (Exception ex) {
                                final String message = ex.getMessage();
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        logTextView.append("\n");
                                        logTextView.append(message);
                                    }
                                });
                            }
                        }
                    }).start();
                } else {
                    logTextView.append("Fail to connect network [" + ssid + "], please check ssid and password, and try it later.\n");
                }
            }
        } catch (Exception e) {
            logTextView.append("发生异常:" + e.getMessage());
            logTextView.append("程序终止");
            return;
        }
    }

    private boolean isGpsOpen() {
        LocationManager locationManager = (LocationManager) WifiActivity.this.getSystemService(WifiActivity.this.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps|| network) {
            return true;
        }
        return false;
    }

    private WifiConfiguration getExistsWifiConfiguration(String ssid) {
        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration config : configs) {
            if (config.SSID.equals("\""+ssid+"\"")) {
                return config;
            }
        }
        return null;
    }

}
